package noema.serviceTask;

import java.util.Enumeration;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.interceptor.Interceptors;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.drools.runtime.StatefulKnowledgeSession;

import noema.dataModel.AnalysisOutcome;
import noema.interceptor.LoggerInterceptor;
import noema.session.SessionFactory;

@MessageDriven(mappedName = "topic/analysisService", activationConfig = {
		@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
		@ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/analysisService"),
		@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
public class AnalysisHandlerMDB implements MessageListener {

	@EJB
	private SessionFactory sessionFactory;

	@Override
	@Interceptors(LoggerInterceptor.class)
	public void onMessage(Message jmsMess) {
		if (jmsMess instanceof MapMessage) {
			MapMessage mapMess = ((MapMessage) jmsMess);
			Enumeration<?> names;
			Long processInstanceId = null;
			AnalysisOutcome analysisOutcome=new AnalysisOutcome();
			try {
				names = mapMess.getMapNames();
				while (names.hasMoreElements()) {
					String s = (String) names.nextElement();
					if (s.equals("processInstanceId")) {
						processInstanceId = new Long(mapMess.getLong(s));
					}else{
						generateAnalysis(s,analysisOutcome);
					}
				}
			} catch (JMSException e) {
				processInstanceId = null;
				e.printStackTrace();
				return;
			}
			if (processInstanceId != null) {
				StatefulKnowledgeSession ksession=sessionFactory.getSessionByProcessInstanceId(processInstanceId);
				ksession.signalEvent("analysisOutcomeReadySignal", analysisOutcome, processInstanceId);
			}
		}

	}

	private void generateAnalysis(String s, AnalysisOutcome analysisOutcome) {
		System.out.println("Generating analysis("+s+")....");
	}

}
